package com.eurobcoin.controller;

import java.util.List;
import java.util.Locale;

import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.eurobcoin.invite.InviteManager;
import com.eurobcoin.invite.InviteSendResponse;
import com.eurobcoin.manager.DAOManager;
import com.eurobcoin.user.UserManager;
import com.eurobcoin.user.UserModel;
import com.eurobcoin.worker.MailWorker;

@Controller
@RequestMapping("/invitations")
public class InvitationsController {

	private static final Logger logger = LoggerFactory.getLogger(InvitationsController.class);
	
	private static final String SEND_INVITATIONS_VIEW = "invitations/send_invitations";
	
	@Autowired
	private UserManager userManager;
	
	@Autowired
	private DAOManager daoManager;
	
	@Autowired
	private MailWorker mailWorker;
	
	@Autowired
	private InviteManager inviteManager;
	
	@RequestMapping(value="/index.html", method=RequestMethod.GET)
	public ModelAndView doIndex() throws Exception {
		
		ModelAndView ret = new ModelAndView(SEND_INVITATIONS_VIEW); 
		
		SqlSession sqlSession = this.daoManager.openSession();
		
		List<UserModel> users = this.userManager.getAllUsers(sqlSession);
		ret.addObject("users", users);
		
		sqlSession.close();
		
		return ret;
		
	}
	
	@RequestMapping(value="/send.html", method=RequestMethod.POST)
	public ModelAndView sendInvitation(
			@RequestParam(value="user") Integer invitingUserId, 
			@RequestParam(value="email") String email,
			@RequestParam(value="locale") String locale) throws Exception {
	
		SqlSession sqlSession = this.daoManager.openSession();
		
		boolean commit = false;
		
		ModelAndView ret = new ModelAndView(SEND_INVITATIONS_VIEW);
		
		// TODO: Correjir
		Locale lLocale;
		if("es".equals(locale)) {
			lLocale = new Locale("es");
		}else if("ru".equals(locale)) {
			lLocale = new Locale("ru");
		}else{
			lLocale = new Locale("en");
		}
		
		UserModel userModel = this.userManager.getUserById(sqlSession, invitingUserId);
		
		InviteSendResponse inviteSendResponse = this.inviteManager.sendInvitation(
				sqlSession, 
				lLocale, 
				invitingUserId,
				userModel.getName(),
				email);
		
		String msg;
		
		// TODO: Correjir
		if(inviteSendResponse.getResponseCode() == InviteSendResponse.RESP_OK) {
			
			// realizar el envío de la invitación
			this.mailWorker.queueEmail(
					email, 
					email, 
					inviteSendResponse.getInviteEmailSubject(), 
					inviteSendResponse.getInviteEmailBody(), 
					sqlSession);
			
			msg = "La invitación se ha enviado con éxito";
			commit = true;
						
		} else if(inviteSendResponse.getResponseCode() == InviteSendResponse.RESP_NO_INV_AVAILABLE) {
			
			msg = "Este usuario no tiene invitaciones disponibles.";
			commit = false;
			
		} else {
			
			msg = "Se ha producido un error. La invitación no ha sido enviada.";
			commit = false;
			
		}
		
		ret.addObject("message", msg);
		
		List<UserModel> users = this.userManager.getAllUsers(sqlSession);
		ret.addObject("users", users);
		
		if(commit)
			sqlSession.commit();
		
		sqlSession.close();
		
		return ret;
		
	}
	
}
